package ink.feny.security.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import ink.feny.security.property.JwtAuthProperty;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Jwt 工具类
 * @author Feny
 * @date Created in 2021/4/28
 */
@Component
public class JwtService {
    @Autowired
    private JwtAuthProperty property;

    /**
     * 生成令牌
     * @param userId 用户id
     * @author Feny
     * @date 2021/4/28
     */
    public String generateToken(String userId) {
        return Jwts.builder().setSubject(property.getSubject())
                .claim("userId", userId)
                .setIssuedAt(new Date())
                .setExpiration(DateUtil.offsetSecond(DateUtil.date(), property.getExpire()))
                .signWith(SignatureAlgorithm.HS256, property.getSecret()).compact();
    }

    /**
     * 验证令牌是否时间有效
     * @param token 令牌
     * @return 是否有效
     */
    public Boolean validateToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            System.out.println("token过期时间：" + DateUtil.format(expiration, DatePattern.CHINESE_DATE_TIME_PATTERN));
            return new Date().before(expiration);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从令牌中获取认证的唯一标识
     * @param token 令牌
     * @return 用户id
     */
    public String getSubjectFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从令牌中获取数据声明
     * @param token 令牌
     * @return 数据声明
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(property.getSecret()).parseClaimsJws(token).getBody();
    }


}
